<template>
  <div class="cart wrap-content">
    <div class="cart-tt">
      购物车
    </div>
    <div class="cart-content"
         v-if="carList.length > 0">
      <ul class="cart-item"
          v-for="v,i in carList">
        <li class="td cart-item-img">
          <img :src="v.img"
               :alt="v.title">
        </li>
        <li class="td cart-item-tt">
          {{v.title}}
        </li>
        <!-- <li class="tdr cart-item-sum">
          <div class="cart-price">
            <span>
              ￥<i>{{v.sellPrice*v.numbers}}</i>
            </span>
          </div>
        </li> -->
        <li class="tdr cart-item-amount">
          <div class="num">
            <div class="prd-number prd-select">
              数量
              <span @click="jianNum(v.id)">-</span>
              <div class="prd-num">
                <input type="tel"
                       v-model="v.numbers">
              </div>
              <span @click="addNum(v.id)">+</span>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="cart-content"
         v-else>
      <no-item></no-item>
    </div>
    <div class="cart-bottom">
      <div class="add-address"
           @click="showAdInput=true"
           v-if="!hasAddress">
        <span>+</span> 填写联系人信息
      </div>
      <div class="address-info"
           v-else>
        地址：{{this.showAdress().address}} {{this.showAdress().phone}} {{this.showAdress().name}} <span @click="showAdInput=true">更改</span>
      </div>
      <!-- <div class="all-money">
        共计<span>￥<i>{{allMoney}}</i></span>
      </div> -->
    </div>
    <div class="cart-place">
      <div :class="[hasOrder()>0&&this.hasAddress?'place-btn':'disable place-btn']"
           @click='addOrder()'>
        下单
      </div>
    </div>

    <el-dialog title="填写联系人信息"
               :visible.sync="showAdInput"
               width="30%"
               :before-close="handleClose"
               center>
      <div>
        <el-form :model="adrsForm"
                 :rules="rules"
                 ref="adrsForm"
                 label-width="0px">
          <el-form-item prop="name">
            <el-input v-model="adrsForm.name"
                      placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input v-model="adrsForm.phone"
                      placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item prop="address">
            <el-input v-model="adrsForm.address"
                      type="textarea"
                      placeholder="请输入详细地址"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelAdr()">取 消</el-button>
        <el-button type="primary"
                   @click="submitForm('adrsForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import Number from '@/components/Number'
import NoItem from '@/components/NoItem'
import { fetchAddOrder } from '@/api/common'
import { getStore, removeStore, setStore } from '@/utils/common'
export default {
  data() {
    return {
      //显示填写地址框
      showAdInput: false,
      //有地址
      hasAddress: false,
      adrsForm: {
        name: '',
        phone: '',
        address: '',
      },
      trueAdrs: {
        name: '',
        phone: '',
        address: '',
      },
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
      },
      //可下单
      canPlace: true,
      //唯一下单:id+unix时间戳
      onlyOrder: '',
    }
  },
  mounted() {
    //生成唯一下单码
    if (this.getUserInfo()) {
      this.onlyOrder = `${this.getUserInfo().id}${Math.round(
        new Date().getTime() / 1000
      )}`
    }

    //读取本地地址
    if (this.showAdress()) {
      let _name = this.showAdress().name || ''
      if (_name) {
        this.adrsForm.name = this.showAdress().name
        this.adrsForm.address = this.showAdress().address
        this.adrsForm.phone = this.showAdress().phone
        this.hasAddress = true
      }
    }
  },
  components: {
    Number,
    NoItem,
  },
  methods: {
    ...mapActions(['addNum', 'jianNum']),
    handleClose() {
      this.showAdInput = false
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.hasAddress = true
          this.showAdInput = false
          this.trueAdrs.name = this.adrsForm.name
          this.trueAdrs.address = this.adrsForm.address
          this.trueAdrs.phone = this.adrsForm.phone
          setStore('address', this.adrsForm)
        } else {
          return false
        }
      })
    },
    cancelAdr() {
      if (this.showAdress()) {
        this.adrsForm.name = this.showAdress().name
        this.adrsForm.address = this.showAdress().address
        this.adrsForm.phone = this.showAdress().phone
      }
      this.showAdInput = false
    },
    getUserInfo() {
      const userInfo = JSON.parse(getStore('loginInfo'))
      return userInfo
    },
    showAdress() {
      const address = JSON.parse(getStore('address'))
      return address
    },
    hasOrder() {
      const orderList = JSON.parse(getStore('cart')) || []
      return orderList.length
    },
    async addOrder() {
      if (!this.hasAddress) {
        return false
      } else if (!(this.hasOrder() > 0)) {
        return false
      } else if (!this.token) {
        this.$router.push({ path: '/login' })
        return false
      }

      let orderList = JSON.parse(getStore('cart'))
      let _order = []
      this.trueAdrs.name = this.showAdress().name
      this.trueAdrs.address = this.showAdress().address
      this.trueAdrs.phone = this.showAdress().phone
      this.canPlace = false
      orderList.forEach((item) => {
        const data = {}
        data.id = item.id
        data.numbers = item.numbers
        _order.push(data)
      })
      const res = await fetchAddOrder({
        consumerAddress: this.trueAdrs.address,
        consumerName: this.trueAdrs.name,
        consumerPhone: this.trueAdrs.phone,
        LzNumberIdVo: _order,
        onlyOrder: this.onlyOrder,
      })
      this.canPlace = true
      if (res.status == 200) {
        removeStore('cart')
        this.$store.dispatch('clearCart', [])
        this.$router.push({ path: '/isPlaced' })
        this.$message({
          type: 'success',
          message: '下单成功',
        })
      }
    },
  },
  computed: {
    //computed用来监控自己定义的变量，该变量不在data里面声明，直接在computed里面定义，然后就可以在页面上进行双向数据绑定展示出结果或者用作其他处理；
    ...mapGetters(['carList', 'allMoney', 'token']),
  },
}
</script>

<style lang="scss" scoped>
@import '@/theme/mixin';
.cart {
  margin-top: 30px;
  &-tt {
    height: 20px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #0e1b2f;
    font-size: 16px;
    margin-bottom: 20px;
  }
  &-item {
    border-radius: 9px;
    border: 1px solid #c5c7cb;
    padding: 20px;
    box-sizing: content-box;
    margin-bottom: 20px;
    @include clearfix();
    .td {
      float: left;
      min-height: 60px;
      overflow: hidden;
    }
    .tdr {
      float: right;
      min-height: 60px;
      line-height: 60px;
      overflow: hidden;
    }
    &-img {
      img {
        display: block;
        width: 60px;
        height: 60px;
        border-radius: 3px;
      }
    }
    &-tt {
      width: 365px;
      font-size: 14px;
      color: $tt;
      margin-left: 20px;
    }
    &-amount {
      width: 150px;
      margin-left: 100px;
    }
    &-sum {
      width: 50px;
    }
  }
  &-price {
    span {
      color: #d04a4a;
      font-size: 14px;
    }
    i {
      font-style: inherit;
      font-size: 16px;
    }
  }
  &-bottom {
    padding-bottom: 20px;
    border-bottom: 1px solid #dedede;
    @include clearfix();
  }
  .add-address {
    display: inline-block;
    padding: 10px 13px;
    font-size: 14px;
    border-radius: 6px;
    color: $blue;
    border: 1px dotted $blue;
    cursor: pointer;
    span {
      font-size: 16px;
    }
  }

  .all-money {
    float: right;
    font-size: 20px;
    span {
      color: #d04a4a;
      font-size: 20px;
    }
    i {
      font-style: inherit;
      font-size: 30px;
    }
  }
  .cart-place {
    padding: 80px 0;
    @include clearfix();
  }

  .address-info {
    font-size: 16px;
    span {
      cursor: pointer;
      font-weight: 400;
      color: #1681f1;
    }
  }
  .place-btn {
    float: right;
    width: 130px;
    height: 40px;
    line-height: 40px;
    color: #fff;
    text-align: center;
    background: #d04a4a;
    border-radius: 6px;
    cursor: pointer;
  }
  .disable {
    background: #d2d4d6;
  }
}
</style>